#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QtWidgets/QApplication>
#include <QFileInfo>
#include <QDebug>

#include "meta_center_server_ui.h"
#include "logger.h"

#define SQLITE_DB "p2p_sqlite.db"
#define META_CENTER_SERVER_LISTEN_PORT 8010

MetaCenterServerUi::MetaCenterServerUi(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle("P2P MetaCenterServer");

    /// 把所有控件 都创建出来
    ContentListWidget = new QListWidget;

    myWidget = new QWidget;
    PortLabel = new QLabel("端口:");
    PortLineEdit = new QLineEdit;
    CreateBtn = new QPushButton("打开服务器");

    resourceTree = new QTreeWidget();
    resourceTree->setHeaderLabel("在线用户");
    resourceTree->clear();

    ///栅格布局,
    mainLayout = new QGridLayout();

    mainLayout->addWidget(ContentListWidget,0,0,1,2);
    mainLayout->addWidget(PortLabel,1,0);
    mainLayout->addWidget(PortLineEdit,1,1);
    mainLayout->addWidget(CreateBtn,2,0,1,2);
    mainLayout->addWidget(resourceTree,0,2,3,1);
    myWidget->setLayout(mainLayout);
    this->setCentralWidget(myWidget);

    port = META_CENTER_SERVER_LISTEN_PORT;
    PortLineEdit->setText(QString::number(port));

    // 打开服务器的按钮： 单击事件信号--->slot函数
    connect(CreateBtn,SIGNAL(clicked()),this,SLOT(slotCreateServer()));

    server = nullptr;

}

MetaCenterServerUi::~MetaCenterServerUi()
{
    delete PortLabel;
    delete PortLineEdit;
    delete CreateBtn;
    delete ContentListWidget;
    resourceTree->clear();
    delete resourceTree;
    delete mainLayout;
    delete myWidget;
    if(server != 0)
    {
        server->db.close();
        delete server;
    }
}

extern int g_db;
#define HOSTNAME "localhost"
#define DBNAME "test"
#define USERNAME "root"
#define PASSWORD "123456"

/// 启动 中心服务器,
void MetaCenterServerUi::slotCreateServer()
{
    server = new MetaCenterServer(this, port);

    if( 1 == g_db)
    {
        // USE_MYSQL
        // open mysql database: [ip:dbname:username:password]
        server->db = QSqlDatabase::addDatabase("QMYSQL");
        server->db.setHostName(HOSTNAME);
        server->db.setDatabaseName(DBNAME);
        server->db.setUserName(USERNAME);
        server->db.setPassword(PASSWORD);
        if (!server->db.open())
        {
            QMessageBox::critical(0, QObject::tr("无法打开数据库"), "无法创建数据库连接！ ", QMessageBox::Cancel);
            return;
        }
        MYLOG("mysql hostname:%s database:%s user:%s password:%s", HOSTNAME, DBNAME, USERNAME, PASSWORD);
    }

    else  if( 2 == g_db)
    {
        // USE_SQLITE
        QFileInfo fileInfo(QApplication::applicationDirPath() + "/" + SQLITE_DB);
        if(!fileInfo.isFile())
        {
            QMessageBox::critical(0, QObject::tr("数据库不存在"), "Sqlite p2p_sqlite.db noe exist!", QMessageBox::Cancel);
            return;
        }
        server->db = QSqlDatabase::addDatabase("QSQLITE");
        server->db.setDatabaseName(QApplication::applicationDirPath() + "/" + SQLITE_DB);
        // "E:/MyWorkSpace/QtWorkSpace/p2pFileServer/build-meta_center_server-Desktop_Qt_6_2_1_MinGW_64_bit-Debug/debug/p2p_sqlite.db"
        if (!server->db.open())
        {
            QMessageBox::critical(0, QObject::tr("无法打开数据库"), "Sqlite p2p_sqlite.db noe exist!", QMessageBox::Cancel);
            return;
        }
        // server->db.close();   test save xxx.db,
        MYLOG("Sqlite open p2p_sqlite.db success!");
    }


    connect(server,SIGNAL(UpdateMetaCenterServer(QString,int,MetaCenterServer::MsgKind)),
            this,SLOT(UpdateServerHandle(QString,int,MetaCenterServer::MsgKind)));
    CreateBtn->setEnabled(false);

    MYLOG("login success!");

}


/*
    enum MsgKind{
        UpdateName = 0,
        UPDATEMETA = 1,
        UpdateMsg = 2,
        RemoveName = 3,
    };
*/

/// 更新 中心服务器：根据消息类型
void MetaCenterServerUi::UpdateServerHandle(QString msg, int length, MetaCenterServer::MsgKind flag)
{
    MYLOG("receive UpdateServer flag = %s", MetaCenterServer::MsgKindStr(flag).c_str());

    switch (flag)
    {
    case MetaCenterServer::UpdateMsg:
        ContentListWidget->addItem(msg.left(length));
        break;
    case MetaCenterServer::UPDATEMETA:
        ContentListWidget->addItem(msg + ": update meta");
        break;
    case MetaCenterServer::UpdateName:
    {
        QTreeWidgetItem *item_name = new QTreeWidgetItem(resourceTree);
        item_name->setText(0,msg);
        MYLOG("peernode %s login !", msg.toStdString().c_str());
        break;
    }
    case MetaCenterServer::RemoveName:
    {
        QPoint p(length,0);
        resourceTree->removeItemWidget(resourceTree->itemAt(p),0);
        delete resourceTree->itemAt(p);
        break;
    }
    default:
        break;
    }
    return;
}


